<?php
namespace App\Listener;

use App\Event\SendWelcomeMsg;
use Hyperf\Utils\Codec\Json;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerInterface;
use Hyperf\Redis\RedisFactory;
use Hyperf\DbConnection\Db;

class SendWelcomeMsgListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            SendWelcomeMsg::class,
        ];
    }

    /**
     * 聊天逻辑处理
     */
    public function process(object $event)
    {
        // 事件触发后该监听器要执行的代码写在这里，比如该示例下的发送用户注册成功短信等
        // 直接访问 $event 的 user 属性获得事件触发时传递的参数值
        $user = $event->user;
        $data = $event->data;
        $message = Json::decode($data);
        $redis = $this->container->get(RedisFactory::class)->get('chat');
        $to_id = $redis->get((string)$user->id);

        if ($user->user_type == 2)
            return;

        $content = Db::table('lb_welcome_messages')
            ->where('user_id', $message['to_id'])
            ->where('default', 1)
            ->value('content');
        if ($content) {
            $io = \Hyperf\Utils\ApplicationContext::getContainer()->get(\Hyperf\SocketIOServer\SocketIO::class);
            $io->to($to_id)->emit('broadcastingListen', '{"to_id":"'.$to_id.'", "msg_type":1, "message":"'.$content.'"}');
        }
    }
}
